<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue';
import Gantt from '@/components/DHXGantt/index.vue';
import type { Link, Task } from 'dhtmlx-gantt';
import { nanoid } from 'nanoid';
import type { FormInstance, FormRules } from 'element-plus';
import useTask from '@/stores/modules/testTasks';
import { date_to_str, str_to_date } from '@/utils/time';
import { storeToRefs } from 'pinia';
const timeFormat = date_to_str('%Y-%m-%d %H:%M:%S');
const timeParse = str_to_date('%Y-%m-%d %H:%M:%S');
const taskStore = useTask();
const { taskList } = storeToRefs(taskStore);

const tasks = reactive<{
  data: Task[];
  links: Link[];
}>({
  data: [
    /* {
      id: nanoid(),
      text: "植物大战僵尸",
      start_date: new Date("2023-10-04"),
      end_date: new Date("2023-11-11"),
    },
    {
      id: nanoid(),
      text: "空洞骑士",
      start_date: new Date("2023-10-14"),
      end_date: new Date("2023-11-11"),
    },
    {
      id: nanoid(),
      text: "奥日与森林",
      start_date: new Date("2023-11-04"),
      end_date: new Date("2023-11-11"),
    },
    {
      id: nanoid(),
      text: "气球塔防",
      start_date: new Date("2023-11-14"),
      end_date: new Date("2023-12-12"),
    }, */
  ],
  links: [
    /* { id: "1", source: "1", target: "2", type: "1" },
    { id: "2", source: "2", target: "3", type: "2" },
    { id: "3", source: "3", target: "4", type: "3" },
    { id: "4", source: "1", target: "4", type: "0" }, */
  ],
});
// 整理组装task数据
const initTasksData = (arr: Array<any>) => {
  tasks.data = arr.map((item) => ({
    id: item.id,
    text: item.text,
    start_date: item.start_date,
    end_date: item.end_date,
    desc: item.desc,
    parent: item.parent,
    type: item.type,
    group_id: item.group_id,
    label: item.label,
  }));
};
onMounted(async () => {
  await taskStore.initTaskList();
  initTasksData(taskList.value);
});

// 控制抽屉的显示与隐藏
const drawerShow = ref(false);
// 存储当前双击选择的任务id
const currnetSelectedTaskId = ref<string | number>('');
// 计算 抽屉显示的title
const drawerTitle = computed(() => (currnetSelectedTaskId.value ? '修改任务' : '新建任务'));
// 获取组件gantt实例
const ganttRef = ref();

// 任务双击事件
const taskDblClick = (id: string | number) => {
  currnetSelectedTaskId.value = id;
  drawerShow.value = true;
  const task = ganttRef.value.gantt.getTask(id);
  taskForm.value = task;
};
// 表单实例
const ruleFormRef = ref<FormInstance>();
// 收集表单数据
const taskForm = ref<Partial<Task>>({});
// 表单验证规则
const rules = reactive<FormRules<Partial<Task>>>({
  text: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  start_date: [
    {
      type: 'date',
      required: true,
      message: '请设置开始时间',
      trigger: 'change',
    },
  ],
  end_date: [
    {
      type: 'date',
      required: true,
      message: '请设置结束时间',
      trigger: 'change',
    },
  ],
  desc: [{ required: false, message: '请填写任务描述', trigger: 'blur' }],
});

// 点击新建任务的事件回调
const addTask = () => {
  // 先清空选择的任务ID  确认操作类型为新建任务
  currnetSelectedTaskId.value = '';
  drawerShow.value = true;
  taskForm.value = {};
};

// 点击删除按钮的事件回调
const onDelete = () => {
  // 发送网络请求 删除任务
  taskStore.deleteTask(currnetSelectedTaskId.value as string);
  // 更新页面任务面板
  ganttRef.value.gantt.deleteTask(currnetSelectedTaskId.value);
  // 关闭抽屉
  drawerShow.value = false;
};

// 点击 Save或Create按钮的事件回调
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!', taskForm.value);

      if (currnetSelectedTaskId.value) {
        // 发送网络请求 修改任务
        await taskStore.updateTask({
          id: currnetSelectedTaskId.value as string,
          text: taskForm.value.text,
          start_date: timeFormat(taskForm.value.start_date as Date),
          end_date: timeFormat(taskForm.value.end_date as Date),
          desc: taskForm.value.desc,
        });
        // 更新页面任务面板
        ganttRef.value.gantt.updateTask(currnetSelectedTaskId.value, taskForm.value);
      } else {
        // 发送网络请求 添加任务
        await taskStore.createTask({
          id: nanoid(),
          text: taskForm.value.text,
          start_date: timeFormat(taskForm.value.start_date as Date),
          end_date: timeFormat(taskForm.value.end_date as Date),
          desc: taskForm.value.desc,
        });
        // 更新页面任务面板
        ganttRef.value.gantt.addTask({
          id: nanoid(),
          text: taskForm.value.text,
          start_date: taskForm.value.start_date,
          end_date: taskForm.value.end_date,
          desc: taskForm.value.desc,
        });
      }
      // 关闭抽屉
      drawerShow.value = false;
    } else {
      console.log('error submit!', fields);
    }
  });
};
// 点击Reset按钮的事件回调
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<script lang="ts">
export default {
  name: 'GanttTestView',
};
</script>

<template>
  <section>
    <el-button type="primary" @click="addTask">新建任务</el-button>
    <el-drawer v-model="drawerShow" :show-close="false">
      <template #header="{ titleId, titleClass }">
        <h4 :id="titleId" :class="titleClass">{{ drawerTitle }}</h4>
        <template v-if="currnetSelectedTaskId">
          <el-button type="primary" @click="onSubmit(ruleFormRef)"> save </el-button>
          <el-button type="danger" @click="onDelete">delete</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click.prevent="onSubmit(ruleFormRef)"> Create </el-button>
          <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </template>
      </template>
      <el-form
        :model="taskForm"
        ref="ruleFormRef"
        :rules="rules"
        status-icon
        label-width="120px"
        labelPosition="left"
      >
        <el-form-item label="任务名称" prop="text">
          <el-input v-model="taskForm.text" />
        </el-form-item>
        <el-form-item label="开始时间" prop="start_date">
          <el-date-picker
            v-model="taskForm.start_date"
            type="datetime"
            placeholder="请选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_date">
          <el-date-picker
            v-model="taskForm.end_date"
            type="datetime"
            placeholder="请选择结束时间"
          />
        </el-form-item>
        <el-form-item label="任务描述" prop="desc">
          <el-input v-model="taskForm.desc" type="textarea" />
        </el-form-item>
      </el-form>
    </el-drawer>
    <Gantt ref="ganttRef" v-if="tasks.data.length" :tasks="tasks" @taskDblClick="taskDblClick" />
  </section>
</template>

<style scoped>
/* PC电脑端 */
@media screen and (width <= 1024px) {
}
</style>
